/**
 *<p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2018 soho team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : </li>
 * <li>Version     : 1.0</li>
 * <li>Creation    : 2018年08月04日</li>
 * <li>@author     : ____′↘夏悸</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
const app = {
  state: {
    menus: [],
    keys: [],
    user: {}
  },
  mutations: {
    UPDATE_MENU: (state, menus) => {
      state.menus = menus;
    },
    UPDATE_KEY: (state, keys) => {
      state.keys = keys;
    },
    UPDATE_USER: (state, user) => {
      state.user = user;
    }
  },
  actions: {
    init: ({commit, state}, vm) => {
      return new Promise(resolve => {
        if (state.user.id) {
          resolve();
          return;
        }

        vm.$api('common.init').invoke().then(({data}) => {
          const menusMap = {};
          const menus = [];
          data.menus.forEach(value => {
            menusMap[value.id] = value;
          });
          data.menus.forEach(value => {
            if (value.parentId) {
              if (!menusMap[value.parentId].children) {
                menusMap[value.parentId].children = [];
              }
              menusMap[value.parentId].children.push(value);
            } else {
              menus.push(value);
            }
          });

          commit('UPDATE_MENU', menus);
          commit('UPDATE_KEY', data.keys);
          commit('UPDATE_USER', data.user);

          resolve();
        });
      });
    }
  }
};

export default app;
